// api/ai_role_api/ai_role_list.go
package ai_role_api

import (
	"github.com/gin-gonic/gin"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/models/ctype"
	"muziai-server/service/common"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
	"time"
)

type AiRoleListRequest struct {
	models.Page
	Type int8 `form:"type" json:"type" binding:"required,oneof=1 2 3 4"`
	//1. 角色广场
	//2. 热门角色
	//3. 我创建的角色列表
	//4. 后台角色列表
	Category string `json:"category" form:"category"`
}

type AiRoleListResponse struct {
	models.AiRoleModel
	SessionCount     int    `json:"sessionCount"`
	ChatCount        int    `json:"chatCount"`
	RoleUserNickname string `json:"roleUserNickname,omitempty"` // 创建角色的人
}

func (AiRoleApi) AiRoleListView(c *gin.Context) {
	var cr AiRoleListRequest
	err := c.ShouldBindQuery(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}

	claims, err := jwts.GetClaimsByGin(c)
	if err != nil {
		// 相当于用户没有登陆
		claims = &jwts.Claims{}
	}

	switch claims.Role {
	case ctype.UnLoginRole:
		switch cr.Type {
		case 3, 4:
			res.FailWithMsg(c, "权限错误")
			return
		}
	case ctype.AuthRole:
		switch cr.Type {
		case 4:
			res.FailWithMsg(c, "权限错误")
			return
		}
	}
	query := global.DB.Where("")
	var preloads []string
	switch cr.Type {
	case 1:
		// 角色广场
		query.Where("is_square = ?", true)
		preloads = []string{"UserModel", "ChatList"}
	case 2:
		// 热门角色
		// 根据对话表 查前一天用的最多的前5个角色
		type roleCountGroup struct {
			RoleID uint `gorm:"column:role_id"`
			Count  int  `gorm:"column:c"`
		}

		var roleCountGroupList []roleCountGroup
		beforeDay := time.Now().AddDate(0, 0, -1)
		startTime := beforeDay.Format("2006-01-02") + " 00:00:00"
		endTime := beforeDay.Format("2006-01-02") + " 59:59:59"

		global.DB.Debug().Model(models.ChatModel{}).
			Where("created_at >= ? and created_at <= ?", startTime, endTime).
			Group("role_id").
			Select("role_id", "count(id) as c").
			Order("c desc").
			Limit(5).
			Scan(&roleCountGroupList)
		var roleIDList []uint
		for _, group := range roleCountGroupList {
			roleIDList = append(roleIDList, group.RoleID)
		}

		query.Where("id IN ?", roleIDList).Where("is_square = ?", true)
		preloads = []string{"UserModel"}
	case 3:
		// 我创建的角色
		query.Where("user_id = ?", claims.UserID)
		preloads = []string{"ChatList"}
	case 4:
		// 角色列表
		preloads = []string{"UserModel", "SessionList", "ChatList"}

	}

	_list, count, _ := common.QueryList(models.AiRoleModel{
		Category: cr.Category,
	}, common.Option{
		Page:     cr.Page,
		Likes:    []string{"title"},
		Preloads: preloads,
		Where:    query,
		Sort:     "created_at desc",
	})

	var list = make([]AiRoleListResponse, 0)
	for _, model := range _list {
		switch cr.Type {
		case 1, 2:
			model.Prompt = ""
		}
		list = append(list, AiRoleListResponse{
			AiRoleModel:      model,
			SessionCount:     len(model.SessionList),
			ChatCount:        len(model.ChatList),
			RoleUserNickname: model.UserModel.Nickname,
		})
	}

	res.OkWithList(c, list, count)
}
